﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

namespace Abc.Utils;
public static class FileExtension
{
    /// <summary>
    /// SkiaSharp验证文件是否是图片
    /// </summary>
    /// <param name="file">上传的文件对象</param>
    /// <returns></returns>
    public static bool IsValidFileExtension(this IFormFile file)
    {
        //验证是否图片
        try
        {
            using var memoryStream = new MemoryStream();
            file.CopyTo(memoryStream);
            return FileTypeCheck.IsValidFileExtension(memoryStream, file.FileName.GetExtension());
        }
        catch (Exception e)
        {
            return false;
        }
    }
    /// <summary>
    /// 获取文件扩展名
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static string GetExtension(this string filePath)
    {
        string ext = System.IO.Path.GetExtension(filePath);
        return ext;
    }


    /// <summary>
    /// 文件真实格式检查
    /// </summary>
    /// <param name="filePath">文件完整路径</param>
    /// <returns></returns>
    public static bool IsValidFileExtension(string filePath)
    {
        using var file = File.OpenRead(filePath);
        using var memoryStream = new MemoryStream();
        file.CopyTo(memoryStream);
        byte[] bytes = new byte[160];
        memoryStream.Position = 0;
        memoryStream.Read(bytes, 0, bytes.Length);

        bool pass = FileTypeCheck.IsValidFileExtension(filePath, bytes);

        return pass;
    }
}
